<template>
  <!-- 
  查：
     1：定义api
     2：导入api
     3:进入页面就调用
     4：储存数据并渲染
     5：和分页进行关联处理
  增:
     1:创建新增弹框组件
     2：在父组件使用弹框组件
     3：点击新增按钮打开弹框
     4：完成内部表单布局
     5:表单验证处理
     6:定义新增api
     7：导入新增api
     8：点击确定调用新增api
        调用成功
            a:提示
            b:情况表单数据
            c:关闭弹框
            d:刷新父级列表数据
  删：
    1：点击删除弹出确定框
    2:定义删除api
    3：点击确定时调用删除api
    4：调用成功
          a:提示
          b:刷新父级列表数据
            刷新父级列表数据前判断当前页码>1&& 总数据条数是否只有一条
                如果满足上面二条件   页码--
                再刷新父级列列表数据
  改:
    1:点击修改打开弹框
    2:在弹框组件定义一个遍历用于区分场景  mode="add/edit"
    3：点击新增与修改都修改mode的值为相应的值
    4:数据回显(修改新增弹框组件内form为当前行数据的值(深拷贝))
    5:根据场景调整标题
    6：如果有表单验证调整，还需要分场景调整
    7：定义编辑api
    8：导入
    9:点击确定分场景调用
      调用成功
         a:提示
         b:清空表单数据
         c:关闭弹框
         d:刷新父级列表数据

 -->
  <div class="employees">
    <el-card>
      <div class="top">
        <el-tag><i class="el-icon-info" /> 共{{ page.total }}条记录</el-tag>
        <div class="right">
          <el-button type="danger" size="small" @click="puex"
            >普通excel导出</el-button
          >
          <el-button type="info" size="small">复杂表头excel导出</el-button>
          <el-button
            type="success"
            size="small"
            @click="$route.push('/employees/import')"
            >excel导入</el-button
          >
          <el-button type="primary" size="small" @click="addClick"
            >新增员工</el-button
          >
        </div>
      </div>
    </el-card>
    <el-card>
      <el-table :data="list" border>
        <el-table-column label="序号">
          <template v-slot="{ $index }">
            {{ (page.page - 1) * page.size + $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="username" label="姓名" sortable />
        <el-table-column prop="staffPhoto" label="头像">
          <template v-slot="{ row }">
            <img
              v-errorImg
              class="aubjs"
              :src="row.staffPhoto"
              alt=""
              @click="QuickMark(row.staffPhoto)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="mobile" label="手机号" sortable />
        <el-table-column prop="workNumber" label="工号" />
        <el-table-column
          prop="formOfEmployment"
          label="聘用形式"
          :formatter="formatter"
          sortable
        />
        <el-table-column prop="departmentName" label="部门" sortable />
        <el-table-column prop="timeOfEntry" label="入职时间" sortable>
          <template v-slot="{ row }">
            <div>
              {{ row.timeOfEntry | formatTime }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="enableState" label="状态">
          <template v-slot="{ row }">
            <div v-formatter="row.enableState">{{ row.enableState }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template v-slot="{ row }">
            <el-button
              type="text"
              @click="$router.push('employees/personnel/' + row.id)"
              >查看</el-button
            >
            <el-button type="text">转正</el-button>
            <el-button type="text">调岗</el-button>
            <el-button type="text">离职</el-button>
            <el-button type="text" @click="roleClick(row.id)">角色</el-button>
            <el-button type="text" @click="bul(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="page">
        <el-pagination
          :current-page.sync="page.page"
          :page-sizes="[1, 5, 10, 20, 100, 200, 300, 400]"
          :page-size.sync="page.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>
    <Add :is-show="show" @update:isShow="show = $event" @getData="getData" />
    <el-dialog title="图片二维码" :visible.sync="showCode">
      <div style="text-align:center">
        <canvas ref="canvas" />
      </div>
    </el-dialog>
    <Role ref="role" v-model="roleShow" />
  </div>
</template>
<script>
import { sysUser, sysuserDelete } from '@/api/employees'
import jsCookie from 'js-cookie'
import employees from '@/api/constant/employees'
import Add from './components/add'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import moment from 'moment'
import Qrcode from 'qrcode'
import Role from './components/role'
export default {
  //  注册事件
  components: {
    Add,
    Role
  },
  data () {
    return {
      roleShow: false,
      showCode: false,
      show: false,
      list: [{}],
      page: {
        page: 1,
        size: +jsCookie.get('employess-size') || 1,
        total: 100
      }
    }
  },
  created () {
    this.getData()
  },
  methods: {
    //  页容量
    handleSizeChange (size) {
      // console.log(size, this.page.size)
      jsCookie.set('employess-size', size)
      this.getData()
    },
    //  页码改变
    handleCurrentChange () {
      // console.log(page, this.page.page)
      this.getData()
    },
    async getData () {
      const res = await sysUser(this.page)
      this.list = res.data.data.rows
      this.page.total = res.data.data.total
      console.log('新增员工', res)
    },
    //  聘用形式数据转换
    formatter (row, column, cellValue, index) {
      const findItem = employees.hireType.find(item => item.id === cellValue)
      return findItem ? findItem.value : '-'
    },
    // 新增事件
    addClick () {
      this.show = true
    },
    // 删除员工
    bul (id) {
      this.$confirm('你确定要删除吗？', '提示')
        .then(async () => {
          await sysuserDelete(id)
          this.$message.success('删除成功')
          //  页码处理
          if (this.page.page > 1 && this.list.length === 1) {
            this.page.page--
          }
          this.getData()
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    // 导出excel
    // 拿到所有员工数据
    async puex () {
      const res = await sysUser(this.page)
      const usdList = res.data.data.rows
      //  写出转换规则
      const rules = {
        姓名: 'username',
        头像: 'staffPhoto',
        手机号: 'mobile',
        工号: 'workNumber',
        聘用形式: 'formOfEmployment',
        部门: 'departmentName',
        入职时间: 'timeOfEntry',
        状态: 'enableState'
      }
      //  生产excel响应的data数据
      const listArr = usdList.map(item => {
        const newArr = []
        Object.values(rules).forEach(key => {
          if (key === 'timeOfEntry') {
            newArr.push(moment(item[key]).format('YYYY-MM-DD'))
          } else {
            newArr.push(item[key])
          }
        })
        return newArr
      })
      console.log('所有员工数据', res)
      console.log(usdList)
      //  调用生产excel的方法传入相应的参数值
      export_json_to_excel({
        header: Object.keys(rules),
        data: listArr,
        filename: '员工列表'
      })
    },
    QuickMark (imgSrc) {
      if (!imgSrc) {
        this.$message.warning('没有头像地址!')
        return
      }
      this.showCode = true
      this.$nextTick(() => {
        Qrcode.toCanvas(this.$refs.canvas, imgSrc, {
          width: 300,
          height: 300
        })
      })
    },
    //  角色点击事件
    roleClick (row) {
      this.roleShow = true
      console.log('row', row)
      this.$refs.role.getUserInfo(row)
    }
  }
}
</script>

<style lang="scss" scoped>
.employees {
  padding: 20px;
  .top {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .right {
    display: flex;
  }
  .aubjs {
    width: 50px;
    height: 50px;
    object-fit: cover;
  }
}
</style>
